const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')
const crypto = require('crypto')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
const Users = mongoose.model('Users')



router.get('/', async (ctx, next) => {
  // var username = 'tom'
  // var password = '123'
  // await Users.create({
  //   username, password
  // })

  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
  const stats = await statsfn()
  const commentlast = await Comment.find({})
    .sort({ createdAt: -1 }).limit(3)
  console.log(ctx.session)
  
  await ctx.render('index', {
    title: '图片分享',
    images, stats, username: ctx.session.username, commentlast
  })
})

router.get('/login', async ctx => {
  await ctx.render('login', {})
})

var loginsuc = false
router.post('/login', async ctx => {
  const {username, password} = ctx.request.body
  let user
  let dbhash
  let dbsalt
  if (username.length >= 3) {
    console.log(username)
    // 从数据库中取出对应用户的记录
    user = await Users.find({username: username})
    dbsalt = user[0].salt
    dbhash = user[0].password
    if (user != null && user.length != 0) {
      console.log(loginsuc + "1")
      if (username === user[0].username) {
       // 比对哈希值和盐值
        var comparehash = crypto.pbkdf2Sync(password, dbsalt, 4096, 512, 'RSA-SHA256');
        if (dbhash === comparehash.toString('hex')) {
          loginsuc = true
          console.log('匹配成功')
        }else{
          console.log('匹配失败')
        }
      }
    }
  }
    if (loginsuc) {
    ctx.session.username = username
    ctx.redirect('/?loginsuc=true')
  } else {
    ctx.redirect('/login?loginsuc=false')
  }
})


router.get('/logout', async ctx => {
  ctx.session.username = undefined
  ctx.redirect('/')
})

router.get('/register', async ctx => {
  await ctx.render('register', {})
})

router.post('/register', async ctx => {
  const {username, password} = ctx.request.body
  let registersuc = false
  let ifuser
  if (username.length >= 3) {
    ifuser = await Users.find({username: username})
    if ((!(ifuser !== null) || ifuser.length === 0) && username.length >= 3) {
      registersuc = true
    }
  }
  if (registersuc =true) {
    crypto.randomBytes(32, function (ex, salt) {
      crypto.pbkdf2(password, salt, 4096, 512, 'RSA-SHA256', function (err, key) {
        if (err) throw err
        // 把用户名、密码哈希值、盐值存入数据库
        console.log("注册时存入的hash密码值16进制" + key.toString('hex'))
        console.log("注册时存入的盐值16进制" + salt.toString('hex'))
        key = key.toString('hex')
        // salt = salt.toString('hex')
        Users.create({
          username, password: key, salt
        })
      })
    }) 
    ctx.redirect('/login/?registersuc=true')
  }else{
    ctx.redirect('/register/?registersuc=false')
  }

})

module.exports = router
